package ctrl.action.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ItemBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class SearchServletAction implements ServletAction{
	
	private ServletContext context;	
	public SearchServletAction(ServletContext context) {
		this.context = context;
	}
	
	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String jsp;
		HttpSession session = request.getSession();
		String searchKeyword = request.getParameter(ProjectConstants.PARAMSEARCHKEYWORD);
		Model model = (Model)context.getAttribute(ProjectConstants.PARAMMODEL);
		
		//For returning page after login		
		session.setAttribute(ProjectConstants.PARAMPREVIOUSPAGE, ProjectConstants.PARAMHOME);
		
		if(searchKeyword != null){			
			List<ItemBean> resultList = model.getItemListBySearchKeyword(searchKeyword);
			int size = resultList.size();
			request.setAttribute(ProjectConstants.PARAMSEARCHKEYWORD, searchKeyword);
			request.setAttribute(ProjectConstants.PARAMSEARCHRESULTSIZE, size);
			request.setAttribute(ProjectConstants.PARAMSEARCHRESULT, resultList);
		}
		
		jsp = ProjectConstants.PAGESEARCHRESULT;		
		context.getRequestDispatcher("/" + jsp + ".jspx").forward(request, response);
		
	}

}
